package com.cly.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.domain.IndexImg;
import com.cly.domain.Prod;
import com.cly.feign.IndexImgProdFeign;
import com.cly.mapper.IndexImgMapper;
import com.cly.service.IndexImgService;
import com.cly.vo.IndexImgVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class IndexImgServiceImpl extends ServiceImpl<IndexImgMapper, IndexImg> implements IndexImgService{

    @Autowired
    private IndexImgMapper indexImgMapper;

    @Autowired
    private IndexImgProdFeign indexImgProdFeign;

    /**
     * 分页查询轮播图
     *
     * @param page
     * @param indexImg
     * @return
     */
    @Override
    public Page<IndexImg> findIndexImgPage(Page<IndexImg> page, IndexImg indexImg) {
        return indexImgMapper.selectPage(page, new LambdaQueryWrapper<IndexImg>()
                .eq(!ObjectUtils.isEmpty(indexImg.getStatus()), IndexImg::getStatus, indexImg.getStatus())
                .orderByDesc(IndexImg::getSeq)
        );
    }

    /**
     * 根据id回显轮播图
     * 1.查询轮播图表 根据id
     * 2.如果他有关系到商品id
     * 3.远程调用商品服务 拿到商品的名字 id 图片
     *
     * @param id
     * @return
     */
    @Override
    public IndexImg findIndexImgById(Long id) {
        IndexImg indexImg = indexImgMapper.selectById(id);
        if (ObjectUtils.isEmpty(indexImg)){
            return null;
        }
        //如果有轮播图
        Long prodId = indexImg.getRelation();
        //远程调用商品服务 拿到商品信息map<>
        Prod prod = indexImgProdFeign.getProdById(prodId);
        //远程调用后先判断空
        if (!ObjectUtils.isEmpty(prod)){
            //替换数据
            String prodName = prod.getProdName();
            String pic = prod.getPic();
            indexImg.setProdName(prodName);
            indexImg.setPic(pic);
        }
        //远程调用在不影响大部分业务情况下 不需要报错
        return indexImg;
    }

    /**
     * 加载首页轮播图
     *
     * @return
     */
    @Override
    public List<IndexImgVo> loadFrontIndexImg() {
        //查询数据库 条件必须带上 前台查询 状态
        List<IndexImg> indexImgs = indexImgMapper.selectList(new LambdaQueryWrapper<IndexImg>()
                .eq(IndexImg::getStatus,1)
                .eq(IndexImg::getShopId,1)
                .orderByDesc(IndexImg::getSeq)
        );
        //组合返回值
        List<IndexImgVo> indexImgVos = new ArrayList<>(indexImgs.size() * 2);
        indexImgs.forEach(indexImg -> {
            IndexImgVo indexImgVo = new IndexImgVo();
            //对象拷贝方式
            BeanUtil.copyProperties(indexImg, indexImgVo, true);
            indexImgVos.add(indexImgVo);
        });
        return indexImgVos;
    }


}
